package com.inspector.app.ui.chat;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.example.commen.resource.CommentContect;
import com.inspector.app.R;
import com.inspector.app.databinding.ActivityTaskChatBinding;
import com.inspector.app.di.network.api.UserInfoApi;
import com.inspector.app.ui.base.BaseDJActivity;
import com.inspector.app.ui.chat.adapter.ChatAdapter;
import com.inspector.app.ui.chat.entity.DataBean;
import com.inspector.app.ui.chat.entity.EntityMessageUtils;
import com.inspector.app.ui.chat.entity.HistoryMessageEntity;
import com.inspector.app.ui.chat.entity.ReceiveMessagesEntity;
import com.inspector.app.ui.chat.model.ActivityTaskChatModel;
import com.inspector.app.ui.chat.utils.MediaPlayerManager;
import com.inspector.app.ui.vo.TaskItem;
import com.inspector.app.ui.widget.ITitleBarLayout;
import com.inspector.app.util.CommenArgs;
import com.inspector.app.util.SharedPreferencesUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class HistoryTaskChatActivity extends BaseDJActivity implements View.OnClickListener, ChatAdapter.OnItemListener {

    private ActivityTaskChatBinding viewDataBinding;
    private ActivityTaskChatModel activityTaskChatModel;

    private List<ReceiveMessagesEntity> historyList = new ArrayList<>();
    private String taskId = "59";//任务id
    public static int mSenderId = -1;//个人id
    private ChatAdapter mAdapter;

    private LinearLayoutManager mLinearLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initStatusBar(false);
        viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_task_chat);
        viewDataBinding.setLifecycleOwner(this);
        activityTaskChatModel = new ViewModelProvider(this).get(ActivityTaskChatModel.class);
        TaskItem taskItem = (TaskItem) getIntent().getExtras().get("TaskItem");
        //获取用户信息
        String userJson = SharedPreferencesUtils.getString(CommentContect.SpConstant.UserInfo);
        UserInfoApi.UserInfo userInfo = GsonUtils.fromJson(userJson, CommenArgs.userInfo.getClass());
        //获取个人id
        mSenderId = userInfo != null ? userInfo.getId() : -1;
        if (taskItem != null) {
            //获取任务id
            taskId = taskItem.getId();
        }

        initView();
        observeData();

    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        viewDataBinding.titleBar.setTitle(getString(R.string.title_history_task), ITitleBarLayout.POSITION.LEFT);
        viewDataBinding.titleBar.getLeftIcon().setOnClickListener(this);

        viewDataBinding.importView.setVisibility(View.GONE);//输入框隐藏

        mAdapter = new ChatAdapter(this);
        mLinearLayout = new LinearLayoutManager(this);
        mLinearLayout.setReverseLayout(true);
        viewDataBinding.chatRv.setLayoutManager(mLinearLayout);
        viewDataBinding.chatRv.setAdapter(mAdapter);
        mAdapter.setOnItemListener(this);
    }


    private void observeData() {
        showProgress("加载聊天记录");
        activityTaskChatModel.getHistoryList().observe(this, historyMessageEntities -> {
            if (historyMessageEntities != null) {
                historyList.clear();
                for (int i = 0; i < historyMessageEntities.size(); i++) {
                    HistoryMessageEntity historyMessageEntity = historyMessageEntities.get(i);
                    ReceiveMessagesEntity historyToReceive = EntityMessageUtils.getHistoryToReceive(historyMessageEntity);
                    historyList.add(historyToReceive);
                }
                mAdapter.setData(historyList);

            }
            dismissProgress();

            viewDataBinding.emptyLayout.setVisibility(historyMessageEntities != null && historyMessageEntities.isEmpty() ? View.VISIBLE : View.GONE);
            viewDataBinding.chatRv.setVisibility(historyMessageEntities != null && historyMessageEntities.isEmpty() ? View.GONE : View.VISIBLE);
        });
        activityTaskChatModel.getHistoryMessage(this, taskId);
    }

    @Override
    public void onClick(View view) {
        finish();
    }

    @Override
    public void showImageListener(DataBean dataBean, int position) {
        Intent intent = new Intent(this, PictureActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("DataBean", dataBean);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void showVideoListener(DataBean dataBean, int position) {
        Intent intent = new Intent(this, VideoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("DataBean", dataBean);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void showBotListener(String url, int position) {

    }

    @Override
    public void showFileListener(String url, int position) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri contentUrl = Uri.parse(url);
        intent.setData(contentUrl);
        startActivity(intent);
    }

    /**
     * 播放音频
     *
     * @param animation
     * @param url
     * @param position
     * @param isPlay
     */
    private boolean isPlay = false;

    @Override
    public void startAudioListener(AnimationDrawable animation, String url, int position) {
        if (isPlay) {
            isPlay = false;
            // 停止播放
            // 如果动画正在运行，先停止它
            if (animation.isRunning()) {
                animation.stop();
            }
            // 将动画重置到第一帧
            animation.selectDrawable(0);
            MediaPlayerManager.release();

        } else {
            isPlay = true;
            // 声音播放动画
            animation.start();
            // 播放录音
            MediaPlayerManager.playSound(url, mp -> {
                isPlay = false;
                // 如果动画正在运行，先停止它
                if (animation.isRunning()) {
                    animation.stop();
                }
                // 将动画重置到第一帧
                animation.selectDrawable(0);
                MediaPlayerManager.release();
            });

        }
    }

    @Override
    public void OnItemLongListener(ReceiveMessagesEntity entity, View view, int position) {

    }

    @Override
    public void OnItemResendListener(ReceiveMessagesEntity entity, String file, int position) {

    }
}
